package com.zenithmind.common.pojo.query;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

/**
 * 基础查询DTO
 * 遵循单一职责原则：提供通用的分页和排序功能
 * 遵循开闭原则：支持子类扩展特定查询条件
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Data
@Schema(description = "基础查询DTO")
public class BaseQueryDTO {

    @Schema(description = "页码", example = "1", minimum = "1")
    private Integer pageNum = 1;

    @Schema(description = "每页大小", example = "10", minimum = "1", maximum = "100")
    private Integer pageSize = 10;

    @Schema(description = "排序字段", example = "createTime")
    private String orderBy;

    @Schema(description = "排序方向", example = "DESC", allowableValues = {"ASC", "DESC"})
    private String orderDirection = "DESC";

    @Schema(description = "是否需要总数", example = "true")
    private Boolean needTotal = true;

    @Schema(description = "搜索关键词", example = "文档")
    private String searchKeyword;

    /**
     * 获取偏移量
     */
    public Integer getOffset() {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        return (pageNum - 1) * pageSize;
    }

    /**
     * 获取限制数量
     */
    public Integer getLimit() {
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        if (pageSize > 100) {
            pageSize = 100;
        }
        return pageSize;
    }

    /**
     * 获取排序SQL
     */
    public String getOrderBySql() {
        if (orderBy == null || orderBy.trim().isEmpty()) {
            return "";
        }
        
        String direction = "DESC";
        if ("ASC".equalsIgnoreCase(orderDirection)) {
            direction = "ASC";
        }
        
        return orderBy + " " + direction;
    }

    /**
     * 验证分页参数
     */
    public boolean isValidPagination() {
        return pageNum != null && pageNum > 0 && 
               pageSize != null && pageSize > 0 && pageSize <= 100;
    }

    /**
     * 是否有搜索关键词
     */
    public boolean hasSearchKeyword() {
        return searchKeyword != null && !searchKeyword.trim().isEmpty();
    }

    /**
     * 获取安全的搜索关键词
     */
    public String getSafeSearchKeyword() {
        if (searchKeyword == null) {
            return "";
        }
        return searchKeyword.trim();
    }

    /**
     * 获取当前页码（兼容性方法）
     */
    public Integer getCurrent() {
        return pageNum;
    }

    /**
     * 设置当前页码（兼容性方法）
     */
    public void setCurrent(Integer current) {
        this.pageNum = current;
    }

    /**
     * 获取页面大小（兼容性方法）
     */
    public Integer getSize() {
        return pageSize;
    }

    /**
     * 设置页面大小（兼容性方法）
     */
    public void setSize(Integer size) {
        this.pageSize = size;
    }
}
